package com.qf.sb3.controller;


import com.qf.sb3.entity.Attractions;
import com.qf.sb3.entity.Category;
import com.qf.sb3.service.AttractionsService;
import com.qf.sb3.service.CategoryService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("attractions")
public class AttractionsController {
    @Resource
    private AttractionsService attractionsService;
    @Resource
    private CategoryService categoryService;

    @Value("${my.base.path}")
    private String basePath;


    @GetMapping("/list")
    public String list(Model model){
        List<Attractions> list = attractionsService.QueryAll();
        model.addAttribute("list", list);
        return "/attractions/list";
    }

    @GetMapping("/category")
    public String category(HttpServletRequest request){
        HttpSession session = request.getSession();
        List<Category> list1 = categoryService.QueryAll();


        session.setAttribute("list1", list1);


        return "/attractions/category";
    }

    @GetMapping("/preAdd")
    public String preAdd(Model model){

        return "/attractions/add";
    }

    @PostMapping("/add")
    public String add(Attractions attractions, MultipartFile file){
        if (file.getSize() > 0){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            try {
                file.transferTo(new File(basePath +  uuid));
            } catch (IOException e) {
                e.printStackTrace();
            }
            attractions.setAttractionsPic(uuid);
        }

        attractionsService.add(attractions);

        return "/attractions/add";
    }


}
